var createError = require("http-errors");
var express = require("express");
var path = require("path");
var cookieParser = require("cookie-parser");
var logger = require("morgan");

var indexRouter = require("./routes/index");
var usersRouter = require("./routes/users");

var app = express();

var helmet = require("helmet");
app.use(helmet());

// view engine setup
app.set("views", path.join(__dirname, "views"));
app.set("view engine", "ejs");

app.use(logger("dev"));
app.use(express.json());
app.use(express.urlencoded({ extended: false }));
app.use(cookieParser());
app.use(express.static(path.join(__dirname, "public")));

var bodyParser = require("body-parser");
app.use(bodyParser.urlencoded({ extended: false }));
app.use(bodyParser.json());

// app.js
var expressJWT = require("express-jwt");
var { verToken, singKey, setToken } = require("./token");

// 解析token获取用户信息
app.use(function (req, res, next) {
  var token = req.headers["authorization"];
  if (token == undefined) {
    return next();
  } else {
    verToken(token)
      .then((data) => {
        req.data = data;
        return next();
      })
      .catch((error) => {
        return next();
      });
  }
});

//验证token是否过期并规定哪些路由不用验证
app.use(
  expressJWT.expressjwt({ secret: singKey, algorithms: ["HS256"] }).unless({
    path: [/^\/api\//, "/login"], //不做验证的接口
  })
);

app.use("/", indexRouter);
app.use("/users", usersRouter);

//测试登录接口
app.post("/login", function (req, res, next) {
  var username = req.body.username;
  var password = req.body.password;
  var userid = req.body.userid;
  //生成token
  setToken(username, userid).then((data) => {
    res.json({ token: "Bearer " + data });
  });
});

app.all("*", (req, res, next) => {
  res.header("Access-Control-Allow-Origin", "*");
  res.header("Access-Control-Allow-Headers", "content-type");
  res.header("Access-Control-Allow-Methods", "PUT,POST,GET,DELETE,OPTIONS");
  res.header("Content-Type", "application/json;charset=utf-8");
  next();
});

// catch 404 and forward to error handler
app.use(function (req, res, next) {
  next(createError(404));
});

// error handler
app.use(function (err, req, res, next) {
  // set locals, only providing error in development
  res.locals.message = err.message;
  res.locals.error = req.app.get("env") === "development" ? err : {};

  // render the error page
  res.status(err.status || 500);
  res.render("error");
});

module.exports = app;
